package com.example.admin.controller;

import com.example.admin.service.BlogService;
import com.example.common.Result;
import com.example.xo.pojo.Blog;
import com.example.xo.vo.BlogVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("blog")
public class BlogController {
    @Autowired
    private BlogService blogService;

    @PostMapping("")
    public Result add(@RequestBody Blog blog) {
        //不能为空 trim 去除两端空格，中间的空格去不掉
        if (blog.getTitle() == null || blog.getTitle().trim().length() == 0) {
            log.info("标题为空");
            return Result.error();
        }
        if (blog.getTitle().length() > 50) {
            log.info("标题{}字符个数超过50", blog.getTitle());
            return Result.error();
        }
        if (blog.getCategoryId() == null || blog.getCategoryId().trim().length() == 0) {
            log.info("分类数据丢失");
        }
        if (blog.getAuthor() == null || blog.getAuthor().trim().length() == 0) {
            log.info("作者数据丢失");
        }
        if (blog.getAuthor().length() > 10) {
            log.info("作者名字过长");
            return Result.error();
        }
        if (blog.getContent() == null) {
            log.info("内容不能为空");
            return Result.error();
        }
        return Result.success(blogService.add(blog));
    }

    @GetMapping("findAll")
    public Result findAll() {
        List<BlogVO> all = blogService.findAll();
        return Result.success(all);
    }

    @GetMapping("findById/{id}")
    public Result findById(@PathVariable String id) {
        BlogVO blogvo = blogService.findById(id);
        log.info("{}", blogvo);
        return Result.success(blogvo);
    }

    @PutMapping("update")
    public Result update(@RequestBody Blog blog) {

        boolean res = blogService.update(blog);
        return Result.success(res);
    }

    @DeleteMapping("deleteById/{id}")
    public Result deleteById(@PathVariable String id) {
        boolean result = blogService.deleteById(id);
        return Result.success(result);
    }

    @GetMapping("findPoById/{id}")
    public Result findPoById(@PathVariable String id) {
        Blog blogvo = blogService.findBlogById(id);
        log.info("{}", blogvo);
        return Result.success(blogvo);
    }

}
